<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\goods\category\Group as CategoryGroup;
use app\common\model\MoneyLog;
use app\common\model\order\Goods;
use app\common\model\order\Order;
use app\common\model\User;
use app\common\model\user\Group;
use app\common\model\user\Info;
use think\Db;
use think\Log;

/**
 * 定时任务
 */
class Crontab extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    /**
     * @Author LK
     * @date: 2023-10-20 
     * @ApiTitle (身份升级)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function identity_upgrade()
    {
        Db::startTrans();
        try {
            $info = Info::all(['group_id' => 2]);
            if (!$info) {
                return 'success';
            }
            $time = time();
            foreach ($info as $k => $v) {
                $uid = $v->user_id;

                $user = User::get($uid);
                $group = CategoryGroup::get(['group_id' => 3, 'category_id' => $v->two_cate]);
                //升级条件关闭，直接跳过
                if (!$group) {
                    continue;
                }
                if ($group->status == 'hidden') {
                    continue;
                }


                $direct = User::all(['pid' => $uid]);

                $direct_ids = array_column($direct, 'id');
                //直推人数

                if ($group['direct_num'] > 0 && $group['direct_num'] > count($direct_ids)) {
                    continue;
                }

                //等级大于等于自己用户数量
                $num = Info::whereIn('user_id', $direct_ids)->where('first_cate', $v->first_cate)->where('two_cate', $v->two_cate)->count();
                if ($group['num'] > 0 && $group['num'] > $num) {
                    continue;
                }

                $day = $group->day;
                //团队规定时间消费金额
                $umbrella = User::where("find_in_set({$user->id},paren_ids)")->column('id');
                if ($day > 0) {
                    $the_time = $v->updatetime + $day * 86400;
                    if ($time > $the_time) {
                        $order_ids = Order::where('user_id', $uid)->where('paytime', '>', $v->updatetime)->where('paytime', '<', $the_time)->where('order_status', '>', '0')->column('id');
                        $oids = Order::whereIn('user_id', $umbrella)->where('paytime', '>', $v->updatetime)->where('paytime', '<', $the_time)->where('order_status', '>', '0')->column('id');
                    } else {
                        continue;
                    }
                } else {
                    $order_ids = Order::where('user_id', $uid)->where('paytime', '>', $v->updatetime)->where('order_status', '>', '0')->column('id');
                    $oids = Order::whereIn('user_id', $umbrella)->where('paytime', '>', $v->updatetime)->where('order_status', '>', '0')->column('id');
                }

                //本人规定时间消费金额
                $personal_consumption = Goods::whereIn('order_id', $order_ids)->where('two_cate', $v->two_cate)->sum('pay_fee');
                if ($group['personal_amount'] > 0 && $group['personal_amount'] > $personal_consumption) {
                    continue;
                }
                $team_amount = Goods::whereIn('order_id', $oids)->where('first_cate', $v->first_cate)->where('two_cate', $v->two_cate)->sum('pay_fee');
                if ($group['team_amount'] > 0 && $group['team_amount'] > $team_amount) {
                    continue;
                }

                $v->group_id = 3;
                $expiration_date = config('site.expiration_date');
                $v->expirationtime = strtotime("+" . $expiration_date . " day");
                $v->allowField(true)->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
    /**
     * @Author LK
     * @date: 2023-10-30 
     * @ApiTitle (身份降级)
     * @ApiMethod (GET)
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function demotion()
    {
        Db::startTrans();
        try {
            $info = Info::all();
            $time = time();
            if (!$info) {
                return 'success';
            }
            foreach ($info as $k => $v) {
                $group_id = $v->group_id;
                $group = CategoryGroup::get(['group_id' => $group_id, 'category_id' => $v->two_cate]);
                $set_the_time = $group->set_the_time;

                if ($set_the_time > 0) {
                    $the_time = $v->updatetime + $set_the_time * 86400;

                    if ($time >= $the_time) {
                        $order_ids = Order::where('user_id', $v->user_id)->where('paytime', '>', $v->updatetime)->where('paytime', '<', $the_time)->where('order_status', '>', '0')->column('id');
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
                //本人规定时间消费金额
                $downgrade_amount = Goods::whereIn('order_id', $order_ids)->where('first_cate', $v->first_cate)->where('two_cate', $v->two_cate)->sum('pay_fee');

                if ($group['downgrade_amount'] > 0 && $group['downgrade_amount'] > $downgrade_amount) {
                    if ($group_id == 3) {
                        $expiration_date = config('site.expiration_date');
                        $v->expirationtime = strtotime("+" . $expiration_date . " day");
                        $v->group_id = 2;
                        $v->investment = 0;
                        $v->shareholder = 0;
                        $v->save();
                    } else {
                        $v->delete();
                    }
                    $count = Info::where('user_id', $v->user_id)->count();
                    if ($count <= 0) {
                        User::update(['group_id' => 1], ['id' => $v->user_id]);
                    }
                }
            }
            die;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
    /**
     * @Author LK
     * @date: 2023-10-31 
     * @ApiTitle (身份到期)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function expired_status()
    {
        Db::startTrans();
        try {
            $lists = Info::all(['expirationtime' => ['>', 0]]);
            $time = time();
            if ($lists) {
                foreach ($lists as $v) {
                    if ($v->expirationtime < $time) {
                        $v->delete();
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }

    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (结算分佣)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function settlement_commission()
    {
        Db::startTrans();
        try {
            $order_ids = Goods::where(['is_settle' => 0])->column('order_id');
            $order = Order::all(['order_status' => '30', 'id' => ['in', $order_ids]]);
            if ($order) {
                MoneyLog::commission($order);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("结算分佣:" . $e->getMessage());
            return $e->getMessage();
        }
        return 'success';
    }

    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (自动收货)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function auto_take()
    {
        Db::startTrans();
        try {
            $auto_take_day = config('site.auto_take_time');
            if ($auto_take_day > 0) {
                $take_time = bcmul($auto_take_day, 86400, 0);
            } else {
                $take_time = 0;
            }
            $time = time() - $take_time;
            $order = Order::where(['order_status' => '20'])->whereTime('sendtime', '<', $time)->select();
            if ($order) {
                foreach ($order as $k => $v) {
                    $v->taketime = time();
                    $v->order_status = '30';
                    $v->save();
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
}
